package en.edu.zxj.rabbit.extensions.demo.listener;

import com.rabbitmq.client.Channel;
import en.edu.zxj.rabbit.extensions.demo.constant.Constants;
import en.edu.zxj.rabbit.extensions.demo.model.StudentInfo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-09-20
 * @time: 20:54:53
 */
// @Component
@RabbitListener(queues = Constants.ACK_QUEUE_NAME)
public class AckQueueListener {
    @RabbitListener(queues = Constants.ACK_QUEUE_NAME)
    public void ack(Message message, Channel channel) throws IOException {
        try {
            System.out.printf("收到消息：%s, deliveryTag: %d\n", new String(message.getBody(), "UTF-8"), message.getMessageProperties().getDeliveryTag());
            // 模拟处理失败
            // int num = 1 / 0;
            System.out.println("处理成功");
            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (Exception e) {
            e.printStackTrace();
            // 拒绝消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }

    @RabbitHandler
    public void ack(String msg) throws UnsupportedEncodingException {
        System.out.printf("收到消息：%s\n",msg );
        // 模拟处理失败
        // int num = 1 / 0;
        System.out.println("处理成功");
    }

    @RabbitHandler
    // @RabbitListener(queues = Constants.ACK_QUEUE_NAME)
    public void ack(StudentInfo studentInfo) throws UnsupportedEncodingException {
        System.out.printf("收到消息：%s\n", studentInfo.toString());

        System.out.println("处理成功");
    }
}
